package com.zeroup.matrix;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.DeviceUtils;
import com.bytedance.sdk.open.aweme.CommonConstants;
import com.bytedance.sdk.open.aweme.authorize.model.Authorization;
import com.bytedance.sdk.open.aweme.common.handler.IApiEventHandler;
import com.bytedance.sdk.open.aweme.common.model.BaseReq;
import com.bytedance.sdk.open.aweme.common.model.BaseResp;
import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.api.DouYinOpenApi;
import com.zeroup.matrix.appplication.ZeroneAppliction;
import com.zeroup.matrix.bean.AjaxResult;
import com.zeroup.matrix.bean.LoginVo;
import com.zeroup.matrix.bean.UserInfo;
import com.zeroup.matrix.utile.PermissionsUtil;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.Date;
import java.util.UUID;

public class MainActivity extends BaseActivity implements IApiEventHandler {

    private String imgVcode;


    @BindView(id= R.id.login_btn,click = true)
    Button button;

    @BindView(id=R.id.login_username)
    EditText login_username;

    @BindView(id=R.id.login_pwd)
    EditText login_pwd;

    @BindView(id=R.id.login_yzm_img,click = true)
    ImageView imageView;
    @BindView(id=R.id.login_yzm)
    EditText login_yzm;

    String auth_code = null;

    private String openId = null;

    DouYinOpenApi douYinOpenApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String token = getToken();
        if(!com.blankj.utilcode.util.StringUtils.isEmpty(token)){
            toLogin(this);
            finish();
        }
        douYinOpenApi = DouYinOpenApiFactory.create(this);
        douYinOpenApi.handleIntent(getIntent(), this);
        this.getVCode();
    }



        @Override
    public void setRootView() {
        aty.setContentView(R.layout.login);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.login_btn:
                this.login();
                break;
            case R.id.login_yzm_img:
                this.getVCode();
                break;
        }
    }


    private void login(){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("Loading...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        String user = login_username.getText().toString().trim();
        String pwd = login_pwd.getText().toString().trim();
        String yzm = login_yzm.getText().toString().trim();
        if(StringUtils.isEmpty(user) || StringUtils.isEmpty(pwd)){
            Toast.makeText(MainActivity.this, "请输入账号和密码~", Toast.LENGTH_SHORT).show();
            return;
        }
        KJHttp kjh = new KJHttp();
        LoginVo vo = new LoginVo();
        vo.setUsername(user);
        vo.setPassword(pwd);
        vo.setCheckKey(imgVcode);
        vo.setCaptcha(yzm);
        vo.setSbCode(DeviceUtils.getUniqueDeviceId());
        HttpParams params = new HttpParams();
        params.putJsonParams(JSON.toJSONString(vo));
        kjh.jsonPost(ZeroneAppliction.apiUrl + "sys/login" ,params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
                button.setEnabled(false);
                dialog.show();
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    JSONObject re = (JSONObject) ajaxResult.getResult();
                    bindUserInfo(vo.getSbCode(),re);
                }else{
                    Toast.makeText(MainActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(MainActivity.this, strMsg, Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onFinish() {
                button.setEnabled(true);
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取验证码
     */
    private void getVCode(){
        imgVcode = UUID.randomUUID().toString();
        KJHttp kjh = new KJHttp();
        kjh.get(ZeroneAppliction.apiUrl + "sys/randomImage/" + imgVcode+"?_t="+new Date().getTime(), new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
            }

            @Override
            public void onSuccess(String t) {
                AjaxResult ajaxResult = JSON.parseObject(t, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    byte [] decodedBytes = Base64.decode(ajaxResult.getResult().toString().split(",")[1],
                            Base64.DEFAULT
                    );
                    Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
                    imageView.setImageBitmap(decodedBitmap);
                }else{
                    Toast.makeText(MainActivity.this,"验证码获取有误",Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onPreStart() {
                super.onPreStart();
            }
        });
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d("onResp===>{}",resp.errorCode+"");
        // 授权成功可以获得authCode
        if (resp.getType() == CommonConstants.ModeType.SEND_AUTH_RESPONSE) {
            Authorization.Response response = (Authorization.Response) resp;
            if (resp.isSuccess()) {
                Log.d("onResp===>{}","授权成功，获得权限：" + response.grantedPermissions);
                auth_code = ((Authorization.Response) resp).authCode;
                this.validLogin(DeviceUtils.getUniqueDeviceId(),auth_code);
            } else {
                Log.d("onResp===>{}","授权失败" + response.grantedPermissions);
            }

        }else {
            Log.e("onResp===>授权失败{}",resp.errorMsg);
        }
    }

    @Override
    public void onErrorIntent(Intent intent) {
        // 错误数据
        Log.e("onResp===>{}","intent出错啦");
        finish();
    }


    private void bindUserInfo(String UniqueDeviceId,JSONObject re){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("正在绑定用户...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        JSONObject userInfo = re.getJSONObject("userInfo");
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("openId",openId);
        params.put("userId",userInfo.getString("id"));
        params.put("sbh",UniqueDeviceId);
        KJDB db = KJDB.create(this);
        kjh.get(ZeroneAppliction.apiUrl + "dy/bindDyAccount" ,params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
                dialog.show();
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    UserInfo info = db.findById(userInfo.getString("id"),UserInfo.class);
                    if(info==null){
                        info = userInfo.toJavaObject(UserInfo.class);
                        db.save(info);
                    }else{
                        info.setToken(re.getString("token"));
                        db.update(info);
                    }
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    goVideo(re.getString("token"));
                }else{
                    Toast.makeText(MainActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(MainActivity.this, strMsg, Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    private void validLogin(String sbh,String auth_code){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("登录验证中...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("code",auth_code);
        params.put("sbh",sbh);
        KJDB db = KJDB.create(this);
        kjh.get(ZeroneAppliction.apiUrl + "dy/dyValidLogin" ,params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
                dialog.show();
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    JSONObject re = (JSONObject) ajaxResult.getResult();
                    if(re.getIntValue("isLogin")==1){
                        JSONObject userInfo = re.getJSONObject("userInfo");
                        UserInfo info = db.findById(userInfo.getString("id"),UserInfo.class);
                        if(info==null){
                            info = userInfo.toJavaObject(UserInfo.class);
                            info.setToken(re.getString("token"));
                            db.save(info);
                        }else{
                            info.setToken(re.getString("token"));
                            db.update(info);
                        }
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        goVideo(re.getString("token"));
                    }else  if(re.getIntValue("isLogin")==-1){
                        openId = re.getString("openId");
                    }
                }else{
                    Toast.makeText(MainActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(MainActivity.this, strMsg, Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }


    private void goVideo(String token){
        Intent mIntent = new Intent(MainActivity.this, VediosActivity.class);
        mIntent.putExtra("token",token);
        startActivity(mIntent);
    }
}